import {getLoginInfo} from '@/service';
// import { ITagListType,ITagDetailList} from '@/types';
import { Effect, ImmerReducer, Reducer, Subscription,history } from 'umi';

export interface LoginModelState {
    loginList:object,
    // tagDetailList:ITagDetailList[]
}

export interface TagModelType {
  namespace: 'login';
  state: LoginModelState;
  effects: {
    getLoginInfo:Effect
  };
  reducers: {
    save: Reducer<LoginModelState>;
  };
  subscriptions: { setup: Subscription };
}

const LoginModel: TagModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'login',

  // 数据模型状态，相当于vuex的state
  state: {
    loginList: [],
    // tagDetailList:[]
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    *getLoginInfo({payload}, {call, put}){
      let result = yield getLoginInfo(payload);
      if (result.data){
        localStorage.setItem('token',result.data.token)
        localStorage.setItem('user',JSON.stringify(result.data))
        // window.location.href="/"
        history.push('/')
        yield put({
          type: 'save',
          payload: {
            loginList: result.data,
          }
        })
      }
    }
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        let token = localStorage.getItem('token')
        if(!token){
          if (pathname !== '/login' && pathname !=="/registry") {
            history.replace(`/login?from=${encodeURIComponent(pathname)}`)
          }
        }else{
          if(pathname==='/login'){
            history.replace('/')
          }
        }
        
      });
    },
  },
};

export default LoginModel;
